<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class Goods extends AuthAndBind{
	
	public function __construct(){
		parent::__construct();
	}
	
	/**
	 * 批量删除
	 */
	public function batchDel(){
		if(request() -> isPost()){
			$in = input("post.");
			foreach ($in as $k => $v) {
				if( is_int($v) ) $in[$k] = (string) $v;
			}
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_goods") -> where($where) -> select();
				
				$save['is_delete'] = 1;
				$res = Db::table("gd_goods") -> where($where) -> update($save);
				if( !$res ) returnResults2('-1', '操作失败,请联系管理员');
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量删除商品',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	
	/**
	 * 批量复制商品
	 */
	public function batchCopy(){
		if(request() -> isPost()){
			$in = input("post.");
			foreach ($in as $k => $v) {
				if( is_int($v) ) $in[$k] = (string) $v;
			}
			$bool = is_empty(['user_id', 'id', 'copy_user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$copyUserInfo = Db::table("gd_user") -> where(['id'=>$in['copy_user_id']]) -> find();
				
				$shopWhere[] = ['create_user_id', 'eq', $in['copy_user_id']];
				$shop = Db::table("gd_shop") -> where($shopWhere) -> find();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_goods") -> where($where) -> select();
				
				Db::startTrans();
				foreach ($oldData as $k => $v) {
					$newData = [];
					foreach ($v as $kk => $vv) {
						if( !in_array($kk, ['id', 'user_id']) ){
							$newData[$kk] = is_array($vv) ? json_encode($vv, JSON_UNESCAPED_UNICODE) : $vv;
						}
					}
					
					$newData['shop_id'] = empty($shop) ? 0 : $shop['id'];
					$newData['create_user_id'] = $copyUserInfo['id'];
					$newData['create_user_name'] = $copyUserInfo['nickname'];
					$newData['create_user_type'] = $copyUserInfo['type'];
					$newData['create_date'] = date("Y-m-d H:i:s", time());
					
					$newId1 = Db::table("gd_goods") -> insertGetId($newData);
					if( !$newId1 ) {
						Db::rollback();
						returnResults2('-1', '新增商品失败,请联系管理员');
					}
					
					$oldGoodsSpec = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> select();
					$newGoodsSpec = [];
					foreach ($oldGoodsSpec as $k => $v) {
						foreach ($v as $kk => $vv) {
							if( !in_array($kk, ['id', 'user_id']) ){
								$newGoodsSpec[$k][$kk] = is_array($vv) ? json_encode($vv, JSON_UNESCAPED_UNICODE) : $vv;
							}
							$newGoodsSpec[$k]['goods_id'] = $newId1;
							$newGoodsSpec[$k]['create_user_id'] = $copyUserInfo['id'];
							$newGoodsSpec[$k]['create_user_name'] = $copyUserInfo['nickname'];
							$newGoodsSpec[$k]['create_user_type'] = $copyUserInfo['type'];
							$newGoodsSpec[$k]['create_date'] = date("Y-m-d H:i:s", time());
						}
					}
					$res = Db::table("gd_goods_spec") -> insertAll($newGoodsSpec);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量复制商品',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 批量上下架
	 */
	public function batchEditStatus(){
		if(request() -> isPost()){
			$in = input("post.");
			foreach ($in as $k => $v) {
				if( is_int($v) ) $in[$k] = (string) $v;
			}
			$bool = is_empty(['user_id', 'id', 'status'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				
				$oldData = Db::table("gd_goods") -> where($where) -> select();
				
				Db::startTrans();
				foreach ($oldData as $k => $v) {
					$save['status'] = $in['status'];
					$save = filterArr($save, array_keys($save), $v);
					if( !empty($save) ){
						$re = Db::table("gd_goods") -> where(['id'=>$v['id']]) -> update($save);
						if( !$re ){
							Db::rollback();
							returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
						}
					}
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'商品批量上下架',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 详情
	 */
	public function details(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				
				$data['goods'] = Db::table("gd_goods") -> where($where) -> find();
				
				if( !empty($data['goods']) ){
					$data['goodsSpec'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$data['goods']['id'], 'is_delete'=>0]) -> select();
					$goodsSpecLevelPrice = Db::table("gd_goods_spec_level_price") -> where(['goods_id'=>$data['goods']['id'], 'is_delete'=>0]) -> select();
					if( !empty($data['goodsSpec']) && !empty($goodsSpecLevelPrice) ){
						foreach ($data['goodsSpec'] as $k => $v) {
							$data['goodsSpec'][$k]['goodsSpecLevelPrice'] = [];
							foreach ($goodsSpecLevelPrice as $kk => $vv) {
								if( $v['id'] == $vv['goods_spec_id'] ) $data['goodsSpec'][$k]['goodsSpecLevelPrice'][] = $vv;
							}
						}
					}
					$data['subGoods'] = Db::table("gd_goods_subgoods") -> where(['goods_id'=>$data['goods']['id'], 'is_delete'=>0]) -> select();
					$data['delivery_method'] = Db::table("gd_goods_delivery_method") -> where(['goods_id'=>$data['goods']['id'], 'is_delete'=>0]) -> select();
					$data['historical_sales_quantity'] = Db::table("gd_order") -> where(['goods_id'=>$data['goods']['id']]) -> sum("num");
					
					$data['shopping_history'] = Db::table("gd_order") -> alias('a')
																		-> join('gd_user b', 'a.create_user_id = b.id', 'left') 
																		-> field(['a.goods_name', 'a.total_price', 'a.status', 'a.create_date'=>'order_create_date', 'b.nickname2', 'b.avatar']) 
																		-> where(['goods_id'=>$data['goods']['id']]) -> select();
//					$data['goodsLevelPrice'] = Db::table("gd_goods_level_price") -> where(['goods_id'=>$data['goods']['id'], 'is_delete'=>0]) -> order("level_id asc") -> select();
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取商品详情',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 列表
	 */
	public function index2(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				$where[] = ['is_delete', 'eq', 0];
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['name']) ) $where[] = ['name', 'like', '%' . trim($in['name']) . '%'];
				if( isset($in['is_be_commissioned_to_sell_sth']) ) $where[] = ['is_be_commissioned_to_sell_sth', 'eq', trim($in['is_be_commissioned_to_sell_sth'])];
				if( isset($in['status']) ) $where[] = ['status', 'eq', trim($in['status'])];
				if( isset($in['is_identify']) ) $where[] = ['is_identify', 'eq', trim($in['is_identify'])];
				if( isset($in['shop_id']) ) $where[] = ['shop_id', 'eq', trim($in['shop_id'])];
				if( isset($in['goods_type']) ) {
					if( !in_array($in['goods_type']) ) $in['goods_type'] = [$in['goods_type']];
					$where[] = ['goods_type', 'in', $in['goods_type']];
				}
				if( isset($in['write_off_status']) ) $where[] = ['write_off_status', 'eq', trim($in['write_off_status'])];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', trim($in['create_user_id'])];
				
				if( isset($in['className']) && !empty($in['className']) ){
					$classWhere[] = ['name', 'like', '%'.trim($in['className']).'%'];
					$class = Db::table("gd_classification") -> where($classWhere) -> select();
					if( empty($class) ) returnResults(['code'=>'99999']);
					$where[] = ['class_id1|class_id2|class_id3', 'in', array_column($class, 'id')];
				}

				$data = Db::table("gd_goods") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_goods") -> where($where) -> count();
				
				if( !empty($data) ){
					if( isset($in['village_id']) && $in['village_id'] > 0 ){
						$villageGoods = Db::table("gd_village_goods") -> where(['village_id'=>$in['village_id']]) -> select();
					}
					if( isset($in['collection_type']) && $in['collection_type'] > 0 ){
						$collectionGoods = Db::table("gd_collection_goods") -> where(['type'=>$in['collection_type']]) -> select();
					}
					if( isset($in['divide_into_config_id']) && $in['divide_into_config_id'] > 0 ){
						$divideIntoConfigGoods = Db::table("gd_divide_into_config_goods") -> where(['divide_into_config_id'=>$in['divide_into_config_id']]) -> select();
					}
					
					foreach ($data as $k => $v) {
						$data[$k]['totalInventory'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> sum("num");
						$data[$k]['min_price_protection'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> min("min_price_protection");
						$data[$k]['max_price_protection'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> max("max_price_protection");
						$data[$k]['delivery_method'] = Db::table("gd_goods_delivery_method") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> select();
						$data[$k]['min_price'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> min("price");
						$data[$k]['min_price'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> min("price");
						if( !empty($v['class_id1']) ) $data[$k]['className1'] = Db::table("gd_classification") -> where(['id'=>$v['class_id1']]) -> find()['name'];
						if( !empty($v['class_id2']) ) $data[$k]['clsssName2'] = Db::table("gd_classification") -> where(['id'=>$v['class_id2']]) -> find()['name'];
						if( !empty($v['class_id3']) ) $data[$k]['clsssName3'] = Db::table("gd_classification") -> where(['id'=>$v['class_id3']]) -> find()['name'];
						$data[$k]['className'] = [];
						if( isset($data[$k]['className1']) ) $data[$k]['className'][] = $data[$k]['className1'];
						if( isset($data[$k]['clsssName2']) ) $data[$k]['className'][] = $data[$k]['clsssName2'];
						if( isset($data[$k]['clsssName3']) ) $data[$k]['className'][] = $data[$k]['clsssName3'];
						$data[$k]['className'] = implode(',', $data[$k]['className']);
						$userCollect = Db::table("gd_collect") -> where(['goods_id'=>$v['id'], 'create_user_id'=>$in['user_id']]) -> find();
						$data[$k]['is_collect'] = !empty($userCollect) ? TRUE : FALSE;
						
//						村落
						if( isset($in['village_id']) && $in['village_id'] > 0 ){
							$data[$k]['isVillageGoods'] = FALSE;
							if( isset($villageGoods) && !empty($villageGoods) ){
								foreach ($villageGoods as $kk => $vv) {
									if( $v['id'] == $vv['goods_id'] ) $data[$k]['isVillageGoods'] = TRUE;
								}
							}
						}
//						藏趣
						if( isset($in['collection_type']) && $in['collection_type'] > 0 ){
							$data[$k]['isCollectionGoods'] = FALSE;
							if( isset($collectionGoods) && !empty($collectionGoods) ){
								foreach ($collectionGoods as $kk => $vv) {
									if( $v['id'] == $vv['goods_id'] ) $data[$k]['isCollectionGoods'] = TRUE;
								}
							}
						}
//						分成规则
						if( isset($in['divide_into_config_id']) && $in['divide_into_config_id'] > 0 ){
							$data[$k]['isDivideIntoConfigGoods'] = FALSE;
							if( isset($divideIntoConfigGoods) && !empty($divideIntoConfigGoods) ){
								foreach ($divideIntoConfigGoods as $kk => $vv) {
									if( $v['id'] == $vv['goods_id'] ) $data[$k]['isDivideIntoConfigGoods'] = TRUE;
								}
							}
						}
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取商品列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 列表
	 */
	public function index(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				$where[] = ['is_delete', 'eq', 0];
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'STORE' ) $where[] = ['shop_id', 'eq', $userInfo['shop']['id']];						//商家
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'REGION' ) {																			//代理商
					if( empty($userInfo['shop']) ) returnResults(['code'=>'99999']);
					$where[] = ['shop_id', 'in', array_column($userInfo['shop'], 'id')];
				}
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['name']) ) $where[] = ['name', 'like', '%' . trim($in['name']) . '%'];
				if( isset($in['is_be_commissioned_to_sell_sth']) ) $where[] = ['is_be_commissioned_to_sell_sth', 'eq', trim($in['is_be_commissioned_to_sell_sth'])];
				if( isset($in['status']) ) $where[] = ['status', 'eq', trim($in['status'])];
				if( isset($in['is_identify']) ) $where[] = ['is_identify', 'eq', trim($in['is_identify'])];
				if( isset($in['shop_id']) ) $where[] = ['shop_id', 'eq', trim($in['shop_id'])];
				if( isset($in['goods_type']) ) {
					if( !in_array($in['goods_type']) ) $in['goods_type'] = [$in['goods_type']];
					$where[] = ['goods_type', 'in', $in['goods_type']];
				}
				if( isset($in['write_off_status']) ) $where[] = ['write_off_status', 'eq', trim($in['write_off_status'])];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', trim($in['create_user_id'])];
				
				if( isset($in['className']) && !empty($in['className']) ){
					$classWhere[] = ['name', 'like', '%'.trim($in['className']).'%'];
					$class = Db::table("gd_classification") -> where($classWhere) -> select();
					if( empty($class) ) returnResults(['code'=>'99999']);
					$where[] = ['class_id1|class_id2|class_id3', 'in', array_column($class, 'id')];
				}

				if( isset($in['isGetLowerLevelstore']) && $in['isGetLowerLevelstore'] == 1 ){
//					代理商获取下级商家商品
					$shop = Db::table('gd_shop')	-> alias('a') -> join('gd_user b', 'a.create_user_id = b.id')
														-> field(['a.*']) -> where(['b.type'=>3, 'b.referrer_id'=>$in['user_id']]) -> select();
					if( empty($shop) ) returnResults(['code'=>'99999']);
					$where[] = ['shop_id', 'in', array_column($shop, 'id')];
				}

				$data = Db::table("gd_goods") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_goods") -> where($where) -> count();
				
				if( !empty($data) ){
					if( isset($in['village_id']) && $in['village_id'] > 0 ){
						$villageGoods = Db::table("gd_village_goods") -> where(['village_id'=>$in['village_id']]) -> select();
					}
					if( isset($in['collection_type']) && $in['collection_type'] > 0 ){
						$collectionGoods = Db::table("gd_collection_goods") -> where(['type'=>$in['collection_type']]) -> select();
					}
					if( isset($in['divide_into_config_id']) && $in['divide_into_config_id'] > 0 ){
						$divideIntoConfigGoods = Db::table("gd_divide_into_config_goods") -> where(['divide_into_config_id'=>$in['divide_into_config_id']]) -> select();
					}
					
					foreach ($data as $k => $v) {
						$data[$k]['totalInventory'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> sum("num");
						$data[$k]['min_price_protection'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> min("min_price_protection");
						$data[$k]['max_price_protection'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> max("max_price_protection");
						$data[$k]['delivery_method'] = Db::table("gd_goods_delivery_method") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> select();
						$data[$k]['min_price'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> min("price");
						$data[$k]['min_price'] = Db::table("gd_goods_spec") -> where(['goods_id'=>$v['id'], 'is_delete'=>0]) -> min("price");
						if( !empty($v['class_id1']) ) $data[$k]['className1'] = Db::table("gd_classification") -> where(['id'=>$v['class_id1']]) -> find()['name'];
						if( !empty($v['class_id2']) ) $data[$k]['clsssName2'] = Db::table("gd_classification") -> where(['id'=>$v['class_id2']]) -> find()['name'];
						if( !empty($v['class_id3']) ) $data[$k]['clsssName3'] = Db::table("gd_classification") -> where(['id'=>$v['class_id3']]) -> find()['name'];
						$data[$k]['className'] = [];
						if( isset($data[$k]['className1']) ) $data[$k]['className'][] = $data[$k]['className1'];
						if( isset($data[$k]['clsssName2']) ) $data[$k]['className'][] = $data[$k]['clsssName2'];
						if( isset($data[$k]['clsssName3']) ) $data[$k]['className'][] = $data[$k]['clsssName3'];
						$data[$k]['className'] = implode(',', $data[$k]['className']);
						$userCollect = Db::table("gd_collect") -> where(['goods_id'=>$v['id'], 'create_user_id'=>$in['user_id']]) -> find();
						$data[$k]['is_collect'] = !empty($userCollect) ? TRUE : FALSE;
						
//						村落
						if( isset($in['village_id']) && $in['village_id'] > 0 ){
							$data[$k]['isVillageGoods'] = FALSE;
							if( isset($villageGoods) && !empty($villageGoods) ){
								foreach ($villageGoods as $kk => $vv) {
									if( $v['id'] == $vv['goods_id'] ) $data[$k]['isVillageGoods'] = TRUE;
								}
							}
						}
//						藏趣
						if( isset($in['collection_type']) && $in['collection_type'] > 0 ){
							$data[$k]['isCollectionGoods'] = FALSE;
							if( isset($collectionGoods) && !empty($collectionGoods) ){
								foreach ($collectionGoods as $kk => $vv) {
									if( $v['id'] == $vv['goods_id'] ) $data[$k]['isCollectionGoods'] = TRUE;
								}
							}
						}
//						分成规则
						if( isset($in['divide_into_config_id']) && $in['divide_into_config_id'] > 0 ){
							$data[$k]['isDivideIntoConfigGoods'] = FALSE;
							if( isset($divideIntoConfigGoods) && !empty($divideIntoConfigGoods) ){
								foreach ($divideIntoConfigGoods as $kk => $vv) {
									if( $v['id'] == $vv['goods_id'] ) $data[$k]['isDivideIntoConfigGoods'] = TRUE;
								}
							}
						}
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['collectionGoods'] = isset($collectionGoods) ? $collectionGoods : [];
				$outArr['villageGoods'] = isset($villageGoods) ? $villageGoods : [];
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取商品列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 编辑
	 */
	public function edit(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_goods") -> where($where) -> find();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'原数据有误']);
				
				$save = $in['goods'];
				foreach ($in['goods'] as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						$save[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
				}
				if( $save['is_free_shipping'] == 1 ) $save['carriage'] = '0';
				$save = filterArr($save, array_keys($save), $oldData, ['class_id2', 'class_id3']);
				
//				$newGoodsSpec = [];
//				foreach ($in['goodsSpec'] as $k => $v) {
//					foreach ($v as $kk => $vv) {
//						if( !in_array($kk, ['id', 'user_id']) ){
//							$newGoodsSpec[$k][$kk] = is_array($vv) ? json_encode($vv, JSON_UNESCAPED_UNICODE) : $vv;
//						}
//						$newGoodsSpec[$k]['goods_id'] = $in['id'];
//						$newGoodsSpec[$k]['create_user_id'] = $in['user_id'];
//						$newGoodsSpec[$k]['create_user_name'] = $userInfo['info']['nickname'];
//						$newGoodsSpec[$k]['create_user_type'] = $userInfo['info']['type'];
//						$newGoodsSpec[$k]['create_date'] = date("Y-m-d H:i:s", time());
//					}
//					ksort($newGoodsSpec[$k]);
//				}
				
				Db::startTrans();
//				主商品
				if( !empty($save) ){
					$re = Db::table("gd_goods") -> where($where) -> update($save);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '编辑失败,请联系管理员');
					}
				}
				
//				商品规格
				$oldGoodsSpec = Db::table("gd_goods_spec") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> find();
				if( !empty($oldGoodsSpec) ){
					$delRes = Db::table("gd_goods_spec") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> update(['is_delete'=>1]);
					if( !$delRes ) {
						Db::rollback();
						returnResults2('-1', '删除失败,请联系管理员');
					}
				}
				$oldGoodsSpecLevelPrice = Db::table("gd_goods_spec_level_price") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> find();
				if( !empty($oldGoodsSpecLevelPrice) ){
					$delRes = Db::table("gd_goods_spec_level_price") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> update(['is_delete'=>1]);
					if( !$delRes ) {
						Db::rollback();
						returnResults2('-1', '删除失败,请联系管理员');
					}
				}
				foreach ($in['goodsSpec'] as $k => $v) {
					$newGoodsSpec = [];
					foreach ($v as $kk => $vv) {
						if( !in_array($kk, ['id', 'user_id', 'goodsSpecLevelPrice']) ){
							$newGoodsSpec[$kk] = is_array($vv) ? json_encode($vv, JSON_UNESCAPED_UNICODE) : $vv;
						}
					}
					$newGoodsSpec['cost_price'] = isset($newGoodsSpec['cost_price']) ? $newGoodsSpec['cost_price'] : $newGoodsSpec['price'];
					$newGoodsSpec['num3'] = $newGoodsSpec['num'];
					$newGoodsSpec['goods_id'] = $in['id'];
					$newGoodsSpec['create_user_id'] = $in['user_id'];
					$newGoodsSpec['create_user_name'] = $userInfo['info']['nickname'];
					$newGoodsSpec['create_user_type'] = $userInfo['info']['type'];
					$newGoodsSpec['create_date'] = date("Y-m-d H:i:s", time());
					$newGoodsSpecId = Db::table("gd_goods_spec") -> insertGetId($newGoodsSpec);
					if( !$newGoodsSpecId ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
//					商品规格等级价
					if( isset($v['goodsSpecLevelPrice']) && !empty($v['goodsSpecLevelPrice']) ){
						$newGoodsLevelPrice = [];
						foreach ($v['goodsSpecLevelPrice'] as $k => $v) {
							$newGoodsLevelPrice[$k]['goods_id'] = $in['id'];
							$newGoodsLevelPrice[$k]['goods_spec_id'] = $newGoodsSpecId;
							$newGoodsLevelPrice[$k]['level_id'] = $v['level_id'];
							$newGoodsLevelPrice[$k]['price'] = $v['price'];
							$newGoodsLevelPrice[$k]['create_user_id'] = $in['user_id'];
							$newGoodsLevelPrice[$k]['create_user_name'] = $userInfo['info']['nickname'];
							$newGoodsLevelPrice[$k]['create_user_type'] = $userInfo['info']['type'];
							$newGoodsLevelPrice[$k]['create_date'] = date("Y-m-d H:i:s", time());
						}
						$res = Db::table("gd_goods_spec_level_price") -> insertAll($newGoodsLevelPrice);
						if( !$res ) {
							Db::rollback();
							returnResults2('-1', '新增失败,请联系管理员');
						}
					}
				}
				
//				子商品
				if( isset($in['subGoods']) && !empty($in['subGoods']) ){
					$oldSubGoods = Db::table("gd_goods_subgoods") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> find();
					if( !empty($oldSubGoods) ){
						$delRes = Db::table("gd_goods_subgoods") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> update(['is_delete'=>1]);
						if( !$delRes ) {
							Db::rollback();
							returnResults2('-1', '删除失败,请联系管理员');
						}
					}
					$subGoods = [];
					foreach ($in['subGoods'] as $k => $v) {
						$subGoods[$k]['goods_id'] = $in['id'];
						$subGoods[$k]['sub_goods_id'] = $v['id'];
						$subGoods[$k]['nums'] = $v['nums'];
						$subGoods[$k]['price1'] = $v['price1'];
						$subGoods[$k]['price2'] = $v['price2'];
					}
					$res = Db::table("gd_goods_subgoods") -> insertAll($subGoods);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
//				商品配送方式
				if( isset($in['delivery_method']) && !empty($in['delivery_method']) ){
					$oldDeliveryMethod = Db::table("gd_goods_delivery_method") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> find();
					if( !empty($oldDeliveryMethod) ){
						$delRes = Db::table("gd_goods_delivery_method") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> update(['is_delete'=>1]);
						if( !$delRes ) {
							Db::rollback();
							returnResults2('-1', '删除失败,请联系管理员');
						}
					}
					$newGoodsDeliveryMethod = [];
					foreach ($in['delivery_method'] as $k => $v) {
						$newGoodsDeliveryMethod[$k]['goods_id'] = $in['id'];
						$newGoodsDeliveryMethod[$k]['delivery_method'] = $v;
					}
					$res = Db::table("gd_goods_delivery_method") -> insertAll($newGoodsDeliveryMethod);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
//				商品发货类型
				if( isset($in['delivery_type']) && !empty($in['delivery_type']) ){
					$oldDeliveryType = Db::table("gd_goods_delivery_type") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> find();
					if( !empty($oldDeliveryType) ){
						$delRes = Db::table("gd_goods_delivery_type") -> where(['goods_id'=>$in['id'], 'is_delete'=>0]) -> update(['is_delete'=>1]);
						if( !$delRes ) {
							Db::rollback();
							returnResults2('-1', '删除失败,请联系管理员');
						}
					}
					$newGoodsDeliveryType = [];
					foreach ($in['delivery_type'] as $k => $v) {
						$newGoodsDeliveryType[$k]['goods_id'] = $in['id'];
						$newGoodsDeliveryType[$k]['delivery_type_id'] = $v;
					}
					$res = Db::table("gd_goods_delivery_type") -> insertAll($newGoodsDeliveryType);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'编辑商品',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 新增商品
	 */
	public function add(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'goods'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$shop = [];
				if( $userInfo['info']['type'] == 3 ){
					$shop = Db::table("gd_shop") -> where(['create_user_id'=>$userInfo['info']['id']]) -> find();
				}
				if( $userInfo['info']['create_good_nums'] != '-1' ){
					$goodsWhere = [];
					$goodsWhere[] = ['create_user_id', 'eq', $in['user_id']];
					$goods = Db::table("gd_goods") -> where($goodsWhere) -> count();
					if( $goods > $userInfo['info']['create_good_nums'] ) returnResults2('-1', '操作失败,该账号可创建的商品数已达到上限');
				}
				if( isset($in['goods']['details']) && is_array($in['goods']['details']) && count($in['goods']['details']) > 10 ) returnResults2('-1', '操作失败,商品详情最多只能上传10张图片');
				
				$newData = [];
				foreach ($in['goods'] as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						$newData[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
					// $goods_type = 0;
					// switch ($userInfo['info']['type']) {
					// 	case '1': $goods_type = 1; break;
					// 	case '3': $goods_type = 2; break;
					// }
					if( isset($in['is_be_commissioned_to_sell_sth']) && $in['is_be_commissioned_to_sell_sth'] == 1 ) $goods_type = 3;
					
					$newData['create_user_id'] = $in['user_id'];
					$newData['shop_id'] = empty($shop) ? 0 : $shop['id'];
					// $newData['goods_type'] = $goods_type;
					$newData['create_user_name'] = $userInfo['info']['nickname'];
					$newData['create_user_type'] = $userInfo['info']['type'];
					$newData['create_date'] = date("Y-m-d H:i:s", time());
				}
				
				Db::startTrans();
//				主商品
				$newId1 = Db::table("gd_goods") -> insertGetId($newData);
				if( !$newId1 ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				
//				商品规格
				foreach ($in['goodsSpec'] as $k => $v) {
					$newGoodsSpec = [];
					foreach ($v as $kk => $vv) {
						if( !in_array($kk, ['id', 'user_id', 'goodsSpecLevelPrice']) ){
							$newGoodsSpec[$kk] = is_array($vv) ? json_encode($vv, JSON_UNESCAPED_UNICODE) : $vv;
						}
					}
					$newGoodsSpec['cost_price'] = isset($newGoodsSpec['cost_price']) ? $newGoodsSpec['cost_price'] : $newGoodsSpec['price'];
					$newGoodsSpec['num3'] = $newGoodsSpec['num'];
					$newGoodsSpec['goods_id'] = $newId1;
					$newGoodsSpec['create_user_id'] = $in['user_id'];
					$newGoodsSpec['create_user_name'] = $userInfo['info']['nickname'];
					$newGoodsSpec['create_user_type'] = $userInfo['info']['type'];
					$newGoodsSpec['create_date'] = date("Y-m-d H:i:s", time());
					$newGoodsSpecId = Db::table("gd_goods_spec") -> insertGetId($newGoodsSpec);
					if( !$newGoodsSpecId ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
//					商品规格等级价
					if( isset($v['goodsSpecLevelPrice']) && !empty($v['goodsSpecLevelPrice']) ){
						$newGoodsLevelPrice = [];
						foreach ($v['goodsSpecLevelPrice'] as $k => $v) {
							$newGoodsLevelPrice[$k]['goods_id'] = $newId1;
							$newGoodsLevelPrice[$k]['goods_spec_id'] = $newGoodsSpecId;
							$newGoodsLevelPrice[$k]['level_id'] = $v['level_id'];
							$newGoodsLevelPrice[$k]['price'] = $v['price'];
							$newGoodsLevelPrice[$k]['create_user_id'] = $in['user_id'];
							$newGoodsLevelPrice[$k]['create_user_name'] = $userInfo['info']['nickname'];
							$newGoodsLevelPrice[$k]['create_user_type'] = $userInfo['info']['type'];
							$newGoodsLevelPrice[$k]['create_date'] = date("Y-m-d H:i:s", time());
						}
						$res = Db::table("gd_goods_spec_level_price") -> insertAll($newGoodsLevelPrice);
						if( !$res ) {
							Db::rollback();
							returnResults2('-1', '新增失败,请联系管理员');
						}
					}
				}
				
//				子商品
				if( isset($in['subGoods']) && !empty($in['subGoods']) ){
					$subGoods = [];
					foreach ($in['subGoods'] as $k => $v) {
						$subGoods[$k]['goods_id'] = $newId1;
						$subGoods[$k]['sub_goods_id'] = $v['id'];
						$subGoods[$k]['nums'] = $v['nums'];
						$subGoods[$k]['price1'] = $v['price1'];
						$subGoods[$k]['price2'] = $v['price2'];
					}
					$res = Db::table("gd_goods_subgoods") -> insertAll($subGoods);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
//				商品配送方式
				if( isset($in['delivery_method']) && !empty($in['delivery_method']) ){
					$newGoodsDeliveryMethod = [];
					foreach ($in['delivery_method'] as $k => $v) {
						$newGoodsDeliveryMethod[$k]['goods_id'] = $newId1;
						$newGoodsDeliveryMethod[$k]['delivery_method'] = $v;
					}
					$res = Db::table("gd_goods_delivery_method") -> insertAll($newGoodsDeliveryMethod);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
//				商品发货类型
				if( isset($in['delivery_type']) && !empty($in['delivery_type']) ){
					$newGoodsDeliveryType = [];
					foreach ($in['delivery_type'] as $k => $v) {
						$newGoodsDeliveryType[$k]['goods_id'] = $newId1;
						$newGoodsDeliveryType[$k]['delivery_type_id'] = $v;
					}
					$res = Db::table("gd_goods_delivery_type") -> insertAll($newGoodsDeliveryType);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增商品',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
}

?>